package cn.middle.remote.serialization;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import cn.middle.remote.exception.SerializationException;

public class JsonSerialization implements Serialization {
	
	Gson gson = new GsonBuilder()
			.enableComplexMapKeySerialization()
			.serializeNulls()
			.disableHtmlEscaping()
			.create();

	@Override
	public <T> T decode(byte[] data, TypeGenericity<T> t) throws SerializationException {
		try {
			return gson.fromJson(new String(data), t.isGenericity() ? t : t.getOriginalClass());
		}catch(Exception e) {
			throw new SerializationException("decode data error",e);
		}
		
	}

	@Override
	public byte[] encode(Object obj) throws SerializationException {
		try {
			//obj.getClass().getSimpleName();
			String objJson = gson.toJson(obj);
			return objJson.getBytes();
		}catch(Exception e) {
			throw new SerializationException("encode object error ",e);
		}

	}
	
	
	class ParameterizedTypeImpl implements ParameterizedType {
	    private final Class<?> raw;
	    private final Type[] args;
	    public ParameterizedTypeImpl(Class<?> raw, Type[] args) {
	        this.raw = raw;
	        this.args = args != null ? args : new Type[0];
	    }
	    @Override
	    public Type[] getActualTypeArguments() {
	        return args;
	    }
	    @Override
	    public Type getRawType() {
	        return raw;
	    }
	    @Override
	    public Type getOwnerType() {return null;}
	}

}
